package com.gzz.orchid.common.core.util.crypt;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * HMAC(Hash Message Authentication Code，散列消息鉴别码)
 *
 * @author higmd
 */
public class HMACUtil {
    public static final String KEY_MAC = "HmacMD5";

    /***
     * 初始化HMAC密钥
     */

    public static String initMacKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
        SecretKey secreKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secreKey.getEncoded());
    }

    /**
     * HMAC加密
     */
    public static byte[] encryHmac(byte[] data, String key) {
        SecretKey secreKey = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_MAC);
        Mac mac = null;
        try {
            mac = Mac.getInstance(secreKey.getAlgorithm());
            mac.init(secreKey);
            return mac.doFinal();
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }

    }

}